import { upload } from '../../utils/upload'
import { arrayChunk } from '../../utils/utils'
import { getMatchCode } from '../../http/game'
import { writeFile } from '../../utils/writeFile'
let openStatus = true;
const app = getApp()

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        player_info: {
            type: Array,
            value: () => []
        },
        matchInfo: {
            type: Object,
            value: () => {}
        },
      
        pm_billno: {
            type: String,
            value: ''
        },
        match_id: {
            type: String,
            value: ''
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        flag: false,
        showPlayer: true,
        scoreData: [],
        playerData: [],
        totalData: [],
        qrcode: '',
        selectroundindex:0,
        coverImg: '', //封面图
        scores:[],
        ctx: '', // 上下文实例
        canvas: '', // 画布实例
        dpr: 0,
        staticUrl: app.globalData.staticUrl,
        displayrounds:['','第一轮','第二轮','第三轮','第四轮']
    },
    /**
     * 组件的方法列表
     */
    methods: {
        controlShow(e) {
            let { show } = e.currentTarget.dataset
            if (show) return
            else {
                this.hidePopup()
            }
        },
        selectround(e) {
            const { index } = e.currentTarget.dataset
            
            const scoreData = this.data.scores.playerscorecard.scorecards[index];
           // const list = arrayChunk(scoreData, 9)
            // 前后九
            const totalData = [scoreData.outScoretotal,scoreData.inScoretotal];
            // 总杆数
            const totals =  scoreData.outScoretotal+ scoreData.inScoretotal ; /*scoreData.reduce((sum, a) => {
                return sum + Number(a.score || 0)
            }, 0)*/
            // 总分
            var outtopar = 0 ,intopar = 0;
            scoreData.outScore.forEach(item=>{
               outtopar += parseInt(item.holetopar);
            }) ;
            scoreData.inScore.forEach(item=>{
                intopar += parseInt(item.holetopar);
             }) ;
            const totalScore = outtopar+ intopar;
            /*scoreData.reduce((sum, a) => {
                return sum + Number(a.topar || 0)
            }, 0)*/
            this.setData({
                scoreData,
                totalData,
                totals,
                totalScore,
                selectroundindex:index,
                //playerData
            })
            this.getMatchCode()

            this.selectImg()
        },
        async selectImg() {
            //const res = await upload();
            var that = this;
            wx.chooseImage({
              count: 1,
              success:function(res){
               // const url = app.globalData.host + '/storage/' + res[0]
               console.log(res);
              var  url = res.tempFilePaths[0];
               that.setData({
                    coverImg: url,
                    showPlayer: false
                })
                that.initCanvas()
              }
            })
          
        },
        initCanvas() {
            const query = wx.createSelectorQuery().in(this)
            query.select('#canvas')
                .fields({ node: true, size: true })
                .exec((res) => {
                    const dom = res[0]
                    const canvas = dom.node
                    const ctx = canvas.getContext('2d')
                    const dpr = wx.getSystemInfoSync().pixelRatio
                    canvas.width = dom.width * dpr
                    canvas.height = dom.height * dpr
                    ctx.scale(dpr, dpr);
                    this.setData({
                        canvasDom: dom, // 把canvas的dom对象放到全局
                        canvas: canvas, // 把canvas的节点放到全局
                        ctx: ctx, // 把canvas 2d的上下文放到全局
                        dpr: dpr // 屏幕像素比
                    }, function() {
                        this.drawing() // 开始绘图
                    })
                })
        },
        async getMatchCode() {
            const { match_id, playerData,matchInfo } = this.data;
            var that = this;
            var data = {match_id:matchInfo.matchid,pl_id:playerData.player_id,playername:playerData.trueName,type:6};
            const codeUrl = await getMatchCode(data);
           
           /* writeFile(codeUrl).then(img => { // codeUrl为base64格式的小程序码
                this.setData({
                    qrcodeUrl: img
                })
            }).catch(e => {
                console.log(e);
            });*/
            this.setData({
                qrcodeUrl: codeUrl
            })
        
        },
        // 绘制画面 
        async drawing() {
            wx.showLoading({ title: "生成中" }) // 显示loading
            await this.drawCover();
              await this.drawBg()
              await this.drawText()
              await  this.drawQrcode()
                const { dpr, canvasDom, canvas } = this.data
                setTimeout(() => {
                    wx.canvasToTempFilePath({ //将canvas生成图片
                        canvas: canvas,
                        x: 0,
                        y: 0,
                        width: canvasDom.width * dpr,
                        height: canvasDom.height * dpr,
                        destWidth: canvasDom.width * dpr, //截取canvas的宽度
                        destHeight: canvasDom.height * dpr, //截取canvas的高度
                        fileType: 'jpg',
                        quality: 1,
                        success: (res) => {
                            console.log('生成图片成功：', res)
                            this.setData({
                                imgFilePath: res.tempFilePath,
                            })
                        },
                        fail: function(err) {
                            console.log('生成图片失败：', err)
                        },
                    }, this)
                    wx.hideLoading() // 隐藏loading
                }, 800)
          
          
        },
        getImageInfo: function(url) {
            return new Promise((resolve, reject) => {
                wx.getImageInfo({
                    src: url,
                    success: function(res) {
                        resolve(res);
                    },
                    fail(res) {
                        reject('fail');
                    }
                });
            })
        },
        // 封面图
        drawCover() {
            return new Promise((resolve) => {
                const { canvas, ctx, coverImg, dpr, canvasDom } = this.data
                const coverW = canvasDom.width * 0.6
                const coverH = canvasDom.height * 0.8
                console.log(coverImg);
                let img = canvas.createImage(); //创建img对象
                img.src = coverImg;
                this.getImageInfo(coverImg).then(thumb => {
                    img.onload = () => {
                        this.drawImage(ctx, coverW, coverH, img, thumb.width, thumb.height, canvasDom.width - coverW, 0)
                        resolve()
                    };
                })
            })
        },
        /** 等比例图片方法
         *  ctx  画布
         *  bg_w  图片绘制区域的宽
         *  bg_h  图片绘制区域的高
         *  imgPath  图片路径
         *  imgWidth  图片的原始宽度
         *  imgHeight  图片的原始高度
         *  x  图片绘制的左上角x坐标
         *  y  图片绘制的左上角y坐标
         **/
        drawImage(ctx, bg_w, bg_h, imgPath, imgWidth, imgHeight, x, y) {
            let dWidth = bg_w / imgWidth; // canvas与图片的宽度比例
            let dHeight = bg_h / imgHeight; // canvas与图片的高度比例

            if (imgWidth > bg_w && imgHeight > bg_h || imgWidth < bg_w && imgHeight < bg_h) {
                if (dWidth > dHeight) {
                    ctx.drawImage(imgPath, 0, (imgHeight - bg_h / dWidth) / 2, imgWidth, bg_h / dWidth, x, y, bg_w, bg_h)
                } else {
                    ctx.drawImage(imgPath, (imgWidth - bg_w / dHeight) / 2, 0, bg_w / dHeight, imgHeight, x, y, bg_w, bg_h)
                }
            } else {
                if (imgWidth < bg_w) {
                    ctx.drawImage(imgPath, 0, (imgHeight - bg_h / dWidth) / 2, imgWidth, bg_h / dWidth, x, y, bg_w, bg_h)
                } else {
                    ctx.drawImage(imgPath, (imgWidth - bg_w / dHeight) / 2, 0, bg_w / dHeight, imgHeight, x, y, bg_w, bg_h)
                }
            }
        },
        async drawQrcode() {
          return new Promise((resolve) => {
            const { canvas, ctx, dpr, canvasDom, qrcodeUrl } = this.data
            const diam = 80
            let radius = diam / 2
            const x = canvasDom.width - 10 - diam
            const y = canvasDom.height * 0.8 + (canvasDom.height * 0.2 - diam) / 2
            let qrcode = canvas.createImage(); //创建img对象
            qrcode.src = qrcodeUrl;
            qrcode.onload = () => {
                ctx.save()
                ctx.fillStyle = "#fff";
               // ctx.fillRect(x, y, diam, diam);
                ctx.arc(x + radius, y + radius, radius, 0, 2 * Math.PI)
                ctx.clip()
                ctx.drawImage(qrcode, 0, 0, qrcode.width, qrcode.height, x, y, diam, diam);
               
                ctx.restore()
                ctx.draw();
            };
            resolve()
          })
        },
        drawBg() {
          return new Promise((resolve) => {
            const { canvas, ctx, dpr, canvasDom } = this.data
            const bgW = canvasDom.width * 0.4
            const bgH = canvasDom.height * 0.8
            ctx.save()
            // 绘制黄色 
            ctx.fillStyle = "#299192";
            ctx.fillRect(0, 0, bgW, bgH - 60);
            // 绘制白色 -- 高度60
            ctx.fillStyle = "#FFFFFF";
            ctx.fillRect(0, bgH - 60, bgW, 60);
            // 绘制紫色 高度比例40%
            ctx.fillStyle = "#094E39";
            ctx.fillRect(0, bgH, canvasDom.width, canvasDom.height * 0.2);
            ctx.restore();
            resolve()
          });
        },
         drawText() {
          return new Promise((resolve) => {
            const { matchInfo, ctx, dpr, canvasDom,selectroundindex, playerData, scoreData, totalData, totalScore, totals } = this.data
            const bgW = canvasDom.width * 0.4
            ctx.save();
            // 绘制昵称
            ctx.font = "normal bolder 20px sans-serif"
            ctx.fillStyle = "#fff";
            const num = parseInt(bgW / 14)
            const str = playerData.trueName.slice(0, num)
            const tW = ctx.measureText(str).width
            ctx.fillText(str, bgW / 2 - tW / 2, 10 * dpr)
            // 绘制分隔线
            ctx.moveTo(10, 40)
            ctx.strokeStyle = 'brown'
            ctx.lineTo(bgW - 10, 40)
            ctx.stroke()
            // 绘制球洞分数
            const fontH = (canvasDom.height * 0.8 - 40 - 60 - 70) / 9
            const fontX = canvasDom.width * 0.4 / 2 - 20
            ctx.font = "normal bold 16px sans-serif"
            ctx.fillStyle = "#fff";
            var scoresdata = scoreData.outScore;
            scoresdata =  scoresdata.concat(scoreData.inScore);
            scoresdata.forEach((item, index) => {
                ctx.fillStyle = "#fff";
                const x = fontX - ctx.measureText(item.holeScore || '-').width / 2
                if (index < 9) {
                    ctx.fillText(item.holeScore || '-', x - 24, 64 + fontH * index)
                } else {
                    ctx.fillText(item.holeScore || '-', x + 48, 64 + fontH * (index - 9))
                }
                ctx.strokeStyle = "#fff";
                const scoreX = index < 9 ? fontX - 24 : fontX + 48
                const i = index < 9 ? index : index - 9
                if (item.holetopar == 1 || item.holetopar > 1) {
                    ctx.strokeRect(scoreX - 8, 64 + fontH * i - 14, 16, 16)
                }
                if (item.holetopar > 1) {
                    ctx.strokeRect(scoreX - 10, 64 + fontH * i - 16, 20, 20)
                }
                if (item.holetopar == -1 || item.holetopar < -1) {
                    ctx.beginPath()
                    ctx.arc(scoreX, 64 + fontH * i - 14 + 8, 8, 2 * Math.PI, false)
                    ctx.stroke()
                    ctx.closePath()
                }
                if (item.holetopar < -1) {
                    ctx.beginPath()
                    ctx.arc(scoreX, 64 + fontH * i - 16 + 10, 10, 2 * Math.PI, false)
                    ctx.stroke()
                    ctx.closePath()
                }
            })
            // 绘制前后九洞 高度70
            const halfH = canvasDom.height * 0.8 - 60 - 70 + 30
            const offsetX = fontX - 24 - 16
            const offsetY = fontX + 46 - 16

            ctx.font = "normal bold 14px sans-serif"
            ctx.fillStyle = "#fff";
            ctx.fillText('前九洞', offsetX, halfH)
            ctx.fillText('后九洞', offsetY, halfH)
            ctx.font = "normal bold 22px sans-serif"
            ctx.fillText(totalData[0], offsetX + 10, halfH + 30)
            ctx.fillText(totalData[1], offsetY + 10, halfH + 30)
            // 绘制总分
            const y = canvasDom.height * 0.8 - 60 + 40
            const RW = matchInfo.matchRounds>1?ctx.measureText('R1').width:0;
            const totalsW = ctx.measureText(totals).width
            const scoresW = ctx.measureText(totalScore>0?'+'+totalScore:totalScore).width
            if(matchInfo.matchRounds>1){
            ctx.fillStyle = "#333";
            ctx.fillText('R'+(selectroundindex+1), 10, y)
           }
            ctx.fillStyle =totalScore<0? "#f74f4f":'#333';
            ctx.font = "normal bold 32px sans-serif"
            ctx.fillText(totals, RW + 20, y)

            ctx.fillStyle = "#333";
            ctx.font = "normal bold 22px sans-serif"
            ctx.fillText('(', RW + totalsW + 40, y)

            ctx.fillStyle = totalScore<0?"#f74f4f":'#333';
            ctx.font = "normal bold 22px sans-serif"
            ctx.fillText(totalScore>0?'+'+totalScore:totalScore, RW + 40 + totalsW + 8, y)

            ctx.fillStyle = "#333";
            ctx.font = "normal bold 22px sans-serif"
            ctx.fillText(')', RW + 40 + totalsW + scoresW + 8, y)

            // 绘制标题
            ctx.fillStyle = "#fff";
            ctx.font = "normal bold 16px sans-serif"
            ctx.fillText(matchInfo.matchname, 10, canvasDom.height * 0.8 + 30)

            // 绘制球场
            ctx.fillStyle = "#fff";
            ctx.font =  "normal 300 14px sans-serif";
            ctx.fillText(matchInfo.courseinfo.coursename, 10, canvasDom.height * 0.8 + 62);

            // 绘制日期      
            ctx.fillText(matchInfo.matchstartDate, 10, canvasDom.height * 0.8 + 86)
            ctx.restore()
            resolve()
          })
        },
        saveShareImg(e) {
            let { show } = e.currentTarget.dataset
            if (!show) this.hidePopup()
            var that = this;
            const { imgFilePath } = this.data
            // 获取用户是否开启用户授权相册
            if (!openStatus) {
                wx.openSetting({
                    success: (result) => {
                        if (result) {
                            if (result.authSetting["scope.writePhotosAlbum"] === true) {
                                openStatus = true;
                                wx.saveImageToPhotosAlbum({
                                    filePath: imgFilePath,
                                    success() {
                                      that.setData({
                                            showShareImg: false
                                        })
                                        wx.showToast({
                                            title: '图片保存成功，快去分享到朋友圈吧~',
                                            icon: 'none',
                                            duration: 2000
                                        })
                                    },
                                    fail() {
                                        wx.showToast({
                                            title: '保存失败',
                                            icon: 'none'
                                        })
                                    }
                                })
                            }
                        }
                    },
                    fail: () => {},
                    complete: () => {}
                });
            } else {
                wx.getSetting({
                    success(res) {
                        // 如果没有则获取授权
                        if (!res.authSetting['scope.writePhotosAlbum']) {
                            wx.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success() {
                                    openStatus = true
                                    wx.saveImageToPhotosAlbum({
                                        filePath: imgFilePath,
                                        success() {
                                          that.setData({
                                                showShareImg: false
                                            })
                                            wx.showToast({
                                                title: '图片保存成功，快去分享到朋友圈吧~',
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        },
                                        fail() {
                                            wx.showToast({
                                                title: '保存失败',
                                                icon: 'none'
                                            })
                                        }
                                    })
                                },
                                fail() {
                                    // 如果用户拒绝过或没有授权，则再次打开授权窗口
                                    openStatus = false
                                    console.log('请设置允许访问相册')
                                    wx.showToast({
                                        title: '请设置允许访问相册',
                                        icon: 'none'
                                    })
                                }
                            })
                        } else {
                            // 有则直接保存
                            openStatus = true
                            wx.saveImageToPhotosAlbum({
                                filePath: imgFilePath,
                                success: () => {
                                    wx.showToast({
                                        title: '图片保存成功，快去分享到朋友圈吧~',
                                        icon: 'none',
                                        duration: 2000
                                    })
                                },
                                fail: () => {
                                    wx.showToast({
                                        title: '保存失败',
                                        icon: 'none'
                                    })
                                }
                            })
                        }
                    },
                    fail(err) {
                        console.log(err)
                    }
                })
            }
        },
        showPopup(score,userInfo) {
            if(score&& userInfo){
                this.setData({scores:score,playerData:userInfo});
            }
            this.setData({
                flag: true
            })
        },
        hidePopup() {
            this.setData({
                flag: false,
                showPlayer: true
            })
        },
    }
})